<template>
  <div class="dynamic-form-container">
    <!-- 静态表单项 -->
    <el-card class="static-form">
      <el-form :model="formData" ref="formRef" label-width="100px">
        <el-form-item label="客户名称" prop="customerName"
          :rules="[{ required: true, message: '客户名称不能为空' }]">
          <el-input v-model="formData.customerName" placeholder="请输入客户全名" />
        </el-form-item>
        
        <el-form-item label="订单类型" prop="orderType"
          :rules="{ required: true, message: '请选择订单类型' }">
          <el-select v-model="formData.orderType" placeholder="请选择订单类型">
            <el-option label="普通订单" value="normal" />
            <el-option label="加急订单" value="urgent" />
            <el-option label="预定订单" value="reserve" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 动态表单区域 -->
    <div v-for="(item, index) in formData.items" :key="item.id" class="dynamic-form-item">
      <el-card class="dynamic-card">
        <div class="form-item-header">
          <span>产品 {{ index + 1 }}</span>
          <div class="item-actions">
            <el-button 
              v-if="showCopy && index === formData.items.length - 1"
              type="primary" 
              icon="DocumentCopy" 
              circle 
              size="small"
              @click="duplicateItem(index)"
              title="复制当前产品"
            />
            <el-button 
              type="danger" 
              icon="Delete" 
              circle 
              size="small"
              @click="removeItem(index)"
              title="删除"
              :disabled="!rowCanDelete(item, index)"
            />
          </div>
        </div>
        
        <el-form 
          :model="item" 
          :ref="el => setFormRef(index, el)"
          label-width="100px"
          class="dynamic-form-content">
          <el-form-item 
            label="产品名称" 
            prop="name"
            :rules="[{ required: true, message: '产品名称不能为空' }]">
            <el-input v-model="item.name" placeholder="请输入产品名称">
              <template #append>
                <el-button 
                  type="primary" 
                  icon="Search" 
                  @click="openProductSelector(index)" />
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item 
            label="产品数量" 
            prop="quantity"
            :rules="[
              { required: true, message: '数量不能为空' },
              { type: 'number', min: 1, message: '数量至少为1', trigger: 'blur' }
            ]">
            <el-input-number 
              v-model.number="item.quantity" 
              :min="1" 
              :precision="0" />
          </el-form-item>
          
          <el-form-item 
            label="单价" 
            prop="price"
            :rules="[
              { required: true, message: '价格不能为空' },
              { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
            ]">
            <el-input v-model.number="item.price">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="小计">
            <el-input :value="calculateItemTotal(item)" readonly>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 添加按钮 -->
    <div class="add-item-container">
      <el-button 
        type="primary" 
        plain 
        icon="Plus" 
        @click="addItem"
        :disabled="maxAddNum > 0 && formData.items.length >= maxAddNum">
        添加新产品
      </el-button>
    </div>
    
    <!-- 汇总信息 -->
    <div class="summary-container">
      <el-tag type="info">产品总数: {{ formData.items.length }}</el-tag>
      <el-tag type="success" class="total-tag">
        总计: ¥ {{ calculateTotal }}
      </el-tag>
    </div>
    
    <!-- 提交按钮 -->
    <div class="submit-container">
      <el-button type="primary" @click="submitForm">提交订单</el-button>
      <el-button @click="resetForm">重置表单</el-button>
      <el-button @click="saveAsDraft">保存草稿</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

const formRef = ref(null);
const itemFormRefs = ref([]);

// 设置动态表单引用
const setFormRef = (index, el) => {
  if (el) itemFormRefs.value[index] = el;
};

// 表单数据结构
const formData = reactive({
  customerName: '',
  orderType: 'normal',
  items: [
    {
      id: generateId(),
      name: '',
      quantity: 1,
      price: null
    }
  ]
});

// 生成唯一ID
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
}

// 添加新产品项
const addItem = () => {
  if (maxAddNum.value > 0 && formData.items.length >= maxAddNum.value) {
    ElMessage.warning(`最多只能添加${maxAddNum.value}个产品`);
    return;
  }
  
  formData.items.push({
    id: generateId(),
    name: '',
    quantity: 1,
    price: null
  });
};

// 删除产品项
const removeItem = (index) => {
  if (formData.items.length > 1) {
    formData.items.splice(index, 1);
    // 同步表单引用数组
    itemFormRefs.value.splice(index, 1);
  } else {
    ElMessage.warning('至少需要保留一个产品项');
  }
};

// 复制产品项
const duplicateItem = (index) => {
  const original = formData.items[index];
  formData.items.push({
    ...structuredClone(original),
    id: generateId()
  });
};

// 打开产品选择器
const openProductSelector = (index) => {
  ElMessage.info(`正在打开产品选择器 (项 ${index + 1})`);
  // 实际项目中这里会调用产品选择对话框
};

// 计算单个产品小计
const calculateItemTotal = (item) => {
  if (item.quantity && item.price) {
    return (item.quantity * item.price).toFixed(2);
  }
  return '0.00';
};

// 计算订单总价
const calculateTotal = computed(() => {
  return formData.items.reduce((total, item) => {
    return item.quantity && item.price 
      ? total + item.quantity * item.price 
      : total;
  }, 0).toFixed(2);
});

// 验证所有表单
const validateAllForms = async () => {
  try {
    // 验证静态表单
    await formRef.value.validate();
    
    // 验证所有动态表单
    const results = await Promise.all(
      itemFormRefs.value.map(form => form.validate())
    );
    
    return results.every(valid => valid);
  } catch (error) {
    return false;
  }
};

// 提交表单
const submitForm = async () => {
  const isValid = await validateAllForms();
  if (!isValid) {
    ElMessage.error('请正确填写所有必填字段');
    return;
  }
  
  // 准备提交数据
  const formJson = JSON.stringify(formData);
  console.log('提交数据:', formJson);
  
  ElMessage.success('订单提交成功！');
  
  // 实际项目中这里会有API请求
  // await axios.post('/api/orders', formData);
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  formData.items = [
    {
      id: generateId(),
      name: '',
      quantity: 1,
      price: null
    }
  ];
  itemFormRefs.value = [];
  ElMessage.success('表单已重置');
};

// 保存为草稿
const saveAsDraft = async () => {
  const isValid = await validateAllForms();
  
  // 实际项目中将保存到数据库或localStorage
  localStorage.setItem('order-draft', JSON.stringify(formData));
  
  if (isValid) {
    ElMessage.success('完整表单已保存为草稿');
  } else {
    ElMessage.warning('表单不完整，已保存为草稿');
  }
};

// 组件属性
const props = defineProps({
  showCopy: {
    type: Boolean,
    default: false
  },
  maxAddNum: {
    type: Number,
    default: 0
  },
  rowCanDelete: {
    type: Function,
    default: () => true
  }
});

// 计算属性
const maxAddNum = computed(() => props.maxAddNum);
</script>

<style scoped>
.dynamic-form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.static-form {
  margin-bottom: 20px;
}

.dynamic-form-item {
  margin-bottom: 20px;
}

.dynamic-card {
  transition: all 0.3s ease;
  border-top: 3px solid #409eff;
}

.dynamic-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

.form-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  color: #333;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.dynamic-form-content {
  padding: 15px;
}

.add-item-container {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.summary-container {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-tag {
  font-size: 16px;
  font-weight: bold;
}

.submit-container {
  display: flex;
  justify-content: center;
  gap: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dynamic-form-container {
    padding: 10px;
  }
  
  .form-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .item-actions {
    align-self: flex-end;
  }
  
  .submit-container {
    flex-direction: column;
    align-items: center;
  }
  
  .summary-container {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}
</style>